package com.greentreecs.fms.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.greentreecs.fms.pojo.domain.AccountingRecDO;
import com.greentreecs.fms.pojo.param.TableAttrParam;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * @author 刀氏春秋
 * @date 2023/11/30
 */
public class ReadExcelUtil<T> {
    private final static Logger logger = LoggerFactory.getLogger(ReadExcelUtil.class);

    /**
     * 获取Excel格式报表
     *
     * @param param 报表表格属性参数
     * @return 返回数据
     */
    public List<T> fetchExcelTableData(TableAttrParam param) {
        // 如果不带入时间（如历史表），则不能拼接null字符
        String filename = "";
        if (param.getTime() != null)
            filename = param.getBaseDir() + param.getTableName() + param.getTime() + param.getFileType();
        else
            filename = param.getBaseDir() + param.getTableName() + param.getFileType();

        List<T> results = new LinkedList<>();
        try {
            EasyExcel.read(filename, param.getDoClass(), new ReadListener<T>() {
                @Override
                public void invoke(T obj, AnalysisContext analysisContext) {
                    results.add(obj);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    logger.info("数据表:{}读取完毕", param.getTableName());
                }
            }).headRowNumber(param.getHeaderRowNum()).sheet().doRead();
        } catch (Exception e) {
            logger.error("数据表:{}无法读取，请校验日期参数，文件名:{}", param.getTableName(), filename);
            return null;
        }
        return results;
    }
}